package com.fishingwithme.infrastructure.utils;

import com.fishingwithme.infrastructure.dtos.FileDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.StorageClient1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;

import static com.fishingwithme.infrastructure.utils.CommonUtils.getUserId;

@Slf4j
@Component
public class FileUtils {
    @Autowired
    private StorageClient1 client;

    public FileDto uploadFile(MultipartFile file) {
        try {
            BufferedInputStream bufferedInputStream = IOUtils.buffer(file.getInputStream());
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
            byte[] bytes = bufferedInputStream.readAllBytes();
            Long id = getUserId();
            NameValuePair[] mataList = new NameValuePair[]{
                    new NameValuePair("author", id.toString())
            };

            String url =  client.upload_file1(bytes, fileExtension, mataList);
            return new FileDto(url,fileName, fileExtension);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new RuntimeException(e);
        }
    }
}
